package com.sheng.leetcode.year2022.swordfingeroffer.day02;

import org.junit.Test;

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;

/**
 * @author liusheng
 * @date 2022/09/05
 *
 * 剑指 Offer 06. 从尾到头打印链表
 *
 * 输入一个链表的头节点，从尾到头反过来返回每个节点的值（用数组返回）。
 *
 * 示例 1：
 * 输入：head = [1,3,2]
 * 输出：[2,3,1]
 *
 * 限制：
 *
 * 0 <= 链表长度 <= 10000
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode.cn/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class Sword0006 {

    @Test
    public void test01() {
        ListNode head = new ListNode(1);
        ListNode l1 = new ListNode(3);
        l1.next = new ListNode(2);
        head.next = l1;
        System.out.println(Arrays.toString(new Solution().reversePrint(head)));
    }
}

class Solution {
    public int[] reversePrint(ListNode head) {
        Deque<Integer> deque = new ArrayDeque<>();
        while (head != null && head.next != null) {
            deque.push(head.val);
            head = head.next;
        }
        if (head != null) {
            deque.push(head.val);
        }
        int[] ints = new int[deque.size()];
        for (int i = 0; i < ints.length; i++) {
            ints[i] = deque.pop();
        }
        return ints;
    }
}

// Definition for singly-linked list.
class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }

    ListNode() { }
}

